package qlsl.androiddesign.api.activity.baseactivity;

import android.app.Activity;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;

import org.greenrobot.eventbus.EventBus;

import qlsl.androiddesign.api.manager.ActivityManager;


/**
 * 公共业务逻辑
 * 作者：郑朝军 on 2017/3/18 10:12
 * 邮箱：1250393285@qq.com
 * 公司：武汉智博创享科技有限公司
 */
public abstract class CommonDataBindingActivityBase<P extends CommonContract.IService, B extends ViewDataBinding>
        extends FunctionActivity<P>
{
    private P p;

    public B mViewBinding;

    public Activity activity;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        activity = this;
        if (getLayoutId() > 0)
        {
            ViewGroup rootView = (ViewGroup) getLayoutInflater().inflate(this.getLayoutId(), null, false);
            mViewBinding = DataBindingUtil.bind(rootView);
            setContentView(rootView);
            bindUI(null);
            bindEvent();
        }
    }

    public void onRestart()
    {
        super.onRestart();

    }

    public void onStart()
    {
        super.onStart();
        if (useEventBus())
        {
            EventBus.getDefault().register(this);
        }
    }

    protected void onResume()
    {
        super.onResume();
    }

    @Override
    protected void onPause()
    {
        super.onPause();

    }

    public void onStop()
    {
        super.onStop();

    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        if (useEventBus())
        {
            EventBus.getDefault().register(this);
        }
        if (getP() != null)
        {
            getP().detachV();
        }
        p = null;
    }

    public void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);

    }

    protected void onRestoreInstanceState(Bundle savedInstanceState)
    {
        super.onRestoreInstanceState(savedInstanceState);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        switch (keyCode)
        {
            case KeyEvent.KEYCODE_BACK:
                if (!getLocalClassName().equals(CommonDataBindingActivityBase.class.getName()))
                {// 主页Activity
                    ActivityManager.getInstance().popActivity();
                    return false;
                }
                break;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void bindUI(View rootView)
    {

    }

    @Override
    public void bindEvent()
    {

    }

    protected P getP()
    {
        if (p == null)
        {
            p = newP();
            if (p != null)
            {
                p.attachV(this);
            }
        }
        return p;
    }
}
